//
// Created by 84000 on 2020/12/7.
//

#ifndef PRO3_ECHOIMAGE_H
#define PRO3_ECHOIMAGE_H
#include <muduo/net/TcpServer.h>
#include <boost/bind.hpp>
#include <functional>
#include <muduo/base/Logging.h>
#include "../base/WaterMarkAdder.h"


class ISServer {
public:
    ISServer(muduo::net::EventLoop *loop,
               const muduo::net::InetAddress &listenAddr);

    void start() {
        server_.start();
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn);

    void onMessage(const muduo::net::TcpConnectionPtr &conn,
                   muduo::net::Buffer *buf,
                   muduo::Timestamp time);

    muduo::net::EventLoop *loop_;
    muduo::net::TcpServer server_;
};

ISServer::ISServer(muduo::net::EventLoop *loop, const muduo::net::InetAddress &listenAddr)
        :loop_(loop),
         server_(loop,listenAddr,"ISServer")
{
    server_.setConnectionCallback(
            boost::bind(&ISServer::onConnection, this, _1));
                //std::bind(&ISServer::onConnection, this, _1);
    server_.setMessageCallback(
            boost::bind(&ISServer::onMessage, this, _1, _2, _3));
}

void ISServer::onConnection(const muduo::net::TcpConnectionPtr &conn) {
    LOG_INFO << "ISServer - " << conn->peerAddress().toIpPort() << " ->"
             << conn->localAddress().toIpPort() << " is"
             << (conn->connected() ? "UP" : "DOWN");
}

void ISServer::onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp time) {
    muduo::string msg(buf->retrieveAllAsString());
    LOG_INFO << conn->name() << " echo " << msg.size() << "byte, "
             << "data received at "<<time.toString();
    conn->send(msg);
    iss::WaterMarkAdder adder;
    adder.workOnceByImageDefault("conan.jpg", "logo2.png", "conan_res2.jpg");
}

#endif //PRO3_ECHOIMAGE_H